//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Xml;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins;
namespace DotNetNuke.Modules.Admin.Portals
{
	public partial class SiteWizard : PortalModuleBase
	{
		public enum ContainerType
		{
			Host = 0,
			Portal = 1,
			Folder = 2,
			All = 3
		}
		private void BindContainers()
		{
			ctlPortalContainer.Clear();
			if (chkIncludeAll.Checked) {
				GetContainers(ContainerType.All, "", "");
			} else {
				if (!String.IsNullOrEmpty(ctlPortalSkin.SkinSrc)) {
					string strFolder;
					string strContainerFolder = ctlPortalSkin.SkinSrc.Substring(0, ctlPortalSkin.SkinSrc.LastIndexOf("/"));
					if (strContainerFolder.StartsWith("[G]")) {
						strContainerFolder = strContainerFolder.Replace("[G]Skins/", "Containers\\");
						strFolder = Common.Globals.HostMapPath + strContainerFolder;
						GetContainers(ContainerType.Folder, "[G]", strFolder);
					} else {
						strContainerFolder = strContainerFolder.Replace("[L]Skins/", "Containers\\");
						strFolder = PortalSettings.HomeDirectoryMapPath + strContainerFolder;
						GetContainers(ContainerType.Folder, "[L]", strFolder);
					}
				} else {
					GetContainers(ContainerType.Portal, "", "");
				}
			}
		}
		private void GetContainers(ContainerType type, string skinType, string strFolder)
		{
			UI.Skins.SkinController objSkins = new UI.Skins.SkinController();
			ctlPortalContainer.Width = "500px";
			ctlPortalContainer.Height = "250px";
			ctlPortalContainer.Border = "black 1px solid";
			ctlPortalContainer.Columns = 3;
			ctlPortalContainer.SkinRoot = SkinController.RootContainer;
			switch (type) {
				case ContainerType.Folder:
					ctlPortalContainer.LoadSkins(strFolder, skinType, false);
					break;
				case ContainerType.Portal:
					ctlPortalContainer.LoadPortalSkins(false);
					break;
				case ContainerType.Host:
					ctlPortalContainer.LoadHostSkins(false);
					break;
				case ContainerType.All:
					ctlPortalContainer.LoadAllSkins(false);
					break;
			}
		}
		private void GetSkins()
		{
			UI.Skins.SkinController objSkins = new UI.Skins.SkinController();
			ctlPortalSkin.Width = "500px";
			ctlPortalSkin.Height = "250px";
			ctlPortalSkin.Border = "black 1px solid";
			ctlPortalSkin.Columns = 3;
			ctlPortalSkin.SkinRoot = SkinController.RootSkin;
			ctlPortalSkin.LoadAllSkins(false);
		}
		private void GetTemplates()
		{
			string strFolder;
			strFolder = Common.Globals.HostMapPath;
			if (System.IO.Directory.Exists(strFolder)) {
				string[] fileEntries = System.IO.Directory.GetFiles(strFolder, "*.template");
				foreach (string strFileName in fileEntries) {
					if (Path.GetFileNameWithoutExtension(strFileName) == "admin") {
					} else {
						lstTemplate.Items.Add(Path.GetFileNameWithoutExtension(strFileName));
					}
				}
				if (lstTemplate.Items.Count == 0) {
				}
			}
		}
		private void UseTemplate()
		{
			lstTemplate.Enabled = chkTemplate.Checked;
			optMerge.Enabled = chkTemplate.Checked;
			lblMergeTitle.Enabled = chkTemplate.Checked;
			lblMergeWarning.Enabled = chkTemplate.Checked;
			lblTemplateMessage.Text = "";
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			chkIncludeAll.CheckedChanged += new EventHandler(chkIncludeAll_CheckedChanged);
			chkTemplate.CheckedChanged += new EventHandler(chkTemplate_CheckedChanged);
			lstTemplate.SelectedIndexChanged += new EventHandler(lstTemplate_SelectedIndexChanged);
			Wizard.ActiveStepChanged += new EventHandler(Wizard_ActiveStepChanged);
			Wizard.FinishButtonClick += new System.Web.UI.WebControls.WizardNavigationEventHandler(Wizard_FinishButtonClick);
			Wizard.NextButtonClick += new System.Web.UI.WebControls.WizardNavigationEventHandler(Wizard_NextButtonClick);

			try {
				Wizard.StartNextButtonText = "<img src=\"" + Common.Globals.ApplicationPath + "/images/rt.gif\" border=\"0\" /> " + Localization.GetString("Next", this.LocalResourceFile);
				Wizard.StepNextButtonText = "<img src=\"" + Common.Globals.ApplicationPath + "/images/rt.gif\" border=\"0\" /> " + Localization.GetString("Next", this.LocalResourceFile);
				Wizard.StepPreviousButtonText = "<img src=\"" + Common.Globals.ApplicationPath + "/images/lt.gif\" border=\"0\" /> " + Localization.GetString("Previous", this.LocalResourceFile);
				Wizard.FinishPreviousButtonText = "<img src=\"" + Common.Globals.ApplicationPath + "/images/lt.gif\" border=\"0\" /> " + Localization.GetString("Previous", this.LocalResourceFile);
				Wizard.FinishCompleteButtonText = "<img src=\"" + Common.Globals.ApplicationPath + "/images/save.gif\" border=\"0\" /> " + Localization.GetString("Finish", this.LocalResourceFile);
				if (!Page.IsPostBack) {
					GetTemplates();
					chkTemplate.Checked = false;
					lstTemplate.Enabled = false;
					GetSkins();
					PortalController objPortalController = new PortalController();
					PortalInfo objPortal = objPortalController.GetPortal(PortalId);
					txtPortalName.Text = objPortal.PortalName;
					txtDescription.Text = objPortal.Description;
					txtKeyWords.Text = objPortal.KeyWords;
					urlLogo.Url = objPortal.LogoFile;
					urlLogo.FileFilter = Common.Globals.glbImageFileTypes;
					UseTemplate();
				}
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void chkIncludeAll_CheckedChanged(object sender, System.EventArgs e)
		{
			BindContainers();
		}
		private void chkTemplate_CheckedChanged(object sender, System.EventArgs e)
		{
			if (chkTemplate.Checked) {
				lstTemplate.SelectedIndex = -1;
			}
			UseTemplate();
		}
		private void lstTemplate_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (lstTemplate.SelectedIndex > -1) {
				XmlDocument xmlDoc = new XmlDocument();
				XmlNode node;
				string strTemplatePath = Common.Globals.HostMapPath;
				string strTemplateFile = lstTemplate.SelectedItem.Text + ".template";
				try {
					xmlDoc.Load(strTemplatePath + strTemplateFile);
					node = xmlDoc.SelectSingleNode("//portal/description");
					if (node != null) {
						string message = PortalController.CheckDesktopModulesInstalled(node.CreateNavigator());
                        if(!String.IsNullOrEmpty(message))
                        {
                        	lblTemplateMessage.Text =
                        		String.Format("This template has the following modules that are not installed.<br/>{0}",
                        		              message);
                        }
					} else {
						lblTemplateMessage.Text = "";
					}
					//Check that all modules in template are isntalled
                    // parse portal desktop modules (version 5.0 templates)
                    node = xmlDoc.SelectSingleNode("//portal/portalDesktopModules");
                    if (node != null)
					{
						lblTemplateMessage.Text = String.Format("This template has the following modules that are not installed.<br/>{0}", PortalController.CheckDesktopModulesInstalled(node.CreateNavigator()));
                    }
				} catch(Exception ex) {
					lblTemplateMessage.Text = "Error Loading Template description";
				}
			} else {
				lblTemplateMessage.Text = "";
			}
		}
		protected void Wizard_ActiveStepChanged(object sender, System.EventArgs e)
		{
			switch (Wizard.ActiveStepIndex) {
				case 3:
					BindContainers();
					break;
			}
		}
		protected void Wizard_FinishButtonClick(object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)
		{
			PortalController objPortalController = new PortalController();
			if (lstTemplate.SelectedIndex != -1) {
				string strTemplateFile = lstTemplate.SelectedItem.Text + ".template";
				objPortalController.ProcessResourceFile(PortalSettings.HomeDirectoryMapPath, Common.Globals.HostMapPath + strTemplateFile);
				switch (optMerge.SelectedValue) {
					case "Ignore":
						objPortalController.ParseTemplate(PortalId, Common.Globals.HostMapPath, strTemplateFile, PortalSettings.AdministratorId, PortalTemplateModuleAction.Ignore, false);
						break;
					case "Replace":
						objPortalController.ParseTemplate(PortalId, Common.Globals.HostMapPath, strTemplateFile, PortalSettings.AdministratorId, PortalTemplateModuleAction.Replace, false);
						break;
					case "Merge":
						objPortalController.ParseTemplate(PortalId, Common.Globals.HostMapPath, strTemplateFile, PortalSettings.AdministratorId, PortalTemplateModuleAction.Merge, false);
						break;
				}
			}
			PortalInfo objPortal = objPortalController.GetPortal(PortalId);
			objPortal.Description = txtDescription.Text;
			objPortal.KeyWords = txtKeyWords.Text;
			objPortal.PortalName = txtPortalName.Text;
			objPortal.LogoFile = urlLogo.Url;
			objPortalController.UpdatePortalInfo(objPortal);
			SkinController.SetSkin(SkinController.RootSkin, PortalId, SkinType.Portal, ctlPortalSkin.SkinSrc);
			SkinController.SetSkin(SkinController.RootSkin, PortalId, SkinType.Admin, ctlPortalSkin.SkinSrc);
			SkinController.SetSkin(SkinController.RootContainer, PortalId, SkinType.Portal, ctlPortalContainer.SkinSrc);
			SkinController.SetSkin(SkinController.RootContainer, PortalId, SkinType.Admin, ctlPortalContainer.SkinSrc);
		}
		protected void Wizard_NextButtonClick(object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)
		{
			string strMessage;
			switch (e.CurrentStepIndex) {
				case 1:
					if (lstTemplate.SelectedIndex == -1) {
						if (chkTemplate.Checked) {
							e.Cancel = true;
							lblTemplateMessage.Text = Services.Localization.Localization.GetString("TemplateRequired", this.LocalResourceFile);
						}
					} else {
						string schemaFilename = Server.MapPath("DesktopModules/Admin/Portals/portal.template.xsd");
						string xmlFilename = Common.Globals.HostMapPath + lstTemplate.SelectedItem.Text + ".template";
						PortalTemplateValidator xval = new PortalTemplateValidator();
						if (!xval.Validate(xmlFilename, schemaFilename)) {
							strMessage = Services.Localization.Localization.GetString("InvalidTemplate", this.LocalResourceFile);
							lblTemplateMessage.Text = string.Format(strMessage, lstTemplate.SelectedItem.Text + ".template");
							e.Cancel = true;
						}
					}
					break;
			}
		}
	}
}
